/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.jy.springbootcmsservice.common.base.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jy.springbootcmsservice.common.base.dao.CrudDao;
import com.jy.springbootcmsservice.common.base.entity.DataEntity;
import com.jy.springbootcmsservice.common.base.service.CrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service基类
 * @author ThinkGem
 * @version 2014-05-16
 */
@Transactional(readOnly = true)
public abstract class CrudServiceImpl<D extends CrudDao<T>, T extends DataEntity<T>> extends BaseServiceImpl implements CrudService<T> {
	
	/**
	 * 持久层对象
	 */
	@Autowired
	protected D dao;
	
	/**
	 * 获取单条数据
	 * @param id
	 * @return
	 */
	@Override
	public T get(String id) {
		return dao.get(id);
	}
	
	/**
	 * 获取单条数据
	 * @param entity
	 * @return
	 */
	@Override
	public T get(T entity) {
		return dao.get(entity);
	}
	
	/**
	 * 查询列表数据
	 * @param entity
	 * @return
	 */
	@Override
	public List<T> findList(T entity) {
		return dao.findList(entity);
	}
	
	/**
	 * 查询分页数据
	 * @param entity
	 * @return
	 */
	@Override
	public PageInfo<T> findPage(T entity) {
		int pageNum = entity.getPageNum();
		int pageSize = entity.getPageSize();
		PageHelper.startPage(pageNum, pageSize);
		PageInfo<T> pageInfo = new PageInfo(dao.findList(entity));
		return pageInfo;
	}

	/**
	 * 保存数据（插入或更新）
	 * @param entity
	 */
	@Override
	@Transactional(readOnly = false)
	public int save(T entity) {
		int result;
		if (entity.getIsNewRecord()){
			entity.preInsert();
			result = dao.insert(entity);
		}else{
			entity.preUpdate();
			result = dao.update(entity);
		}
		return result;
	}

	/**
	 * 根据id删除数据
	 * @param id
	 */
	@Transactional(readOnly = false)
	@Override
	public void deleteById(String id) {
		dao.deleteById(id);
	}

	/**
	 * 删除数据
	 * @param entity
	 */
	@Transactional(readOnly = false)
	@Override
	public void delete(T entity) {
		dao.delete(entity);
	}

}
